package com.neu.service.impl;

import java.util.ArrayList;

import com.neu.dao.ImodelDao;
import com.neu.dao.IproblemDao;
import com.neu.dao.IreflectDao;
import com.neu.dao.impl.ModelDao;
import com.neu.dao.impl.ProblemDao;
import com.neu.dao.impl.ReflectDao;
import com.neu.pojo.Model;
import com.neu.pojo.Problem;
import com.neu.pojo.Reflect;
import com.neu.service.ImodelService;

public class ModelService implements ImodelService {
	private ImodelDao modelDao = ModelDao.getInstance();
	private IreflectDao reflectDao = ReflectDao.getInstance();
	private IproblemDao problemDao = ProblemDao.getInstance();
	
	private static ModelService modelService = new ModelService();
	private ModelService() {}
	public static ModelService getInstance() {
		return modelService;
	}
	
	public boolean add(Model m) {
		return this.modelDao.add(m);
	}
	
	public Model search(Model m) {
		return modelDao.search(m);
	}
	
	public Model search(String s) {
		return modelDao.search(s);
	}
	
	@Override
	public ArrayList<Model> list(){
		return modelDao.list();
	}
	
	@Override
	public boolean delete(Model m) {//先删关系再删模板
		if(reflectDao.delete(m)&&modelDao.delete(m)) {
			return true;
		}else {
			return false;
		}
	}
	
	@Override
	public ArrayList<Problem> getProblems(Model m){//用模板，找到所有模板中的问题
		ArrayList<Problem> problems = new ArrayList<>();
		
		ArrayList<Reflect> reflects = reflectDao.list();
		for(Reflect r: reflects) {
			if(r.getMid() == m.getId()) {
				Problem p = problemDao.search(new Problem(r.getPid()));
				if(p!= null)
				problems.add(p);
			}
		}
		return problems;
	}
	
	@Override
	public boolean getLink(Model m,ArrayList<Problem> problems) {
		for(Problem p: problems) {
			if(!this.reflectDao.link(m, p)) {
				return false;
			}
		}
		return true;
	}
}
